package com.zut.blocks.base.util;

import com.zut.blocks.base.common.Login;
import com.zut.blocks.base.exception.CommonException;
import org.slf4j.MDC;

/**
 * @author lxd
 * @date 2020/12/28 10:27
 */
public class UserUtil {
    private final static ThreadLocal<Login> tlUser = new ThreadLocal<>();


    public static final String KEY_USER = "user";


    public static void setUser(Login login) {
        tlUser.set(login);

        // 把用户信息放到log4j
        MDC.put(KEY_USER, login.getId() + "-" + login.getName());
    }

    /**
     * 如果没有登录，返回null
     *
     * @return
     */
    public static Login getUserIfLogin() {
        return tlUser.get();
    }

    /**
     * 如果没有登录会抛出异常
     *
     * @return
     */
    public static Login getUser() {
        Login user = tlUser.get();

        if (user == null) {
            throw new CommonException();
        }

        return user;
    }


    public static void clearAllUserInfo() {
        tlUser.remove();

        MDC.remove(KEY_USER);
    }
}